import os
import re
from distutils.core import setup, Extension
# https://docs.python.org/3/extending/building.html#building


def find_libwwt_config():
  # First try environment var
  defs = os.environ.get("LIBWWT_DEFS", None)
  if defs is not None:
    return defs

  search_paths = ["/usr/lib/", "/usr/local/lib/", "./libwwt/"]
  for path in search_paths:
    filepath = os.path.join(path, "libwwtConfig.sh")
    if os.path.exists(filepath):
      with open(filepath, "r") as f:
        for line in f:
          if line.startswith("LIBWWT_DEFS="):
            lineLen = len(line)
            return line[13:lineLen - 2]

  raise Exception("Could not find configuration (libwwtConfig.sh) for libwwt")


def get_define_macros():
  defs = find_libwwt_config()
  return list(re.findall("-D([a-zA-Z0-9_]+)=?([a-zA-Z0-9_]+)?", defs))


pywwt = Extension(
  "pywwt",
  define_macros      = get_define_macros(),
  libraries          = ["wwt"],
  include_dirs       = ["/usr/include/libwwt/",
                        "/usr/include/libwwt/libwbfs",
                        "/usr/include/libwwt/crypto"],
  sources            = ["src/pywwt-module.c"]
)

def main():
  setup(name         = "pywwt",
        version      = "0.1",
        description  = "Brings the power of WWT (Wiimms WBFS Tool) to Python",
        author       = "CYBERDEViL",
        author_email = "cyberdevil@notabug.org",
        url          = "https://notabug.org/cyberdevil",
        ext_modules  = [pywwt])


if __name__ == "__main__":
  main()
